﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IPCLibrary;
using System.IO;

namespace IPCLibraryTestApp
{
	public partial class Form1 : Form
	{
		private Mailslot _mailslotServer;
		private MailslotClient _mailslotClient;
		private MemoryMappedFile _memoryMappedFile;
		private SharedMemory _sharedMemory;
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			_mailslotServer = new Mailslot("TestName");
			_mailslotClient = new MailslotClient("TestName");
			_memoryMappedFile = new MemoryMappedFile(4096, "TestMapping");
			_sharedMemory = new SharedMemory("data.dll", "data", 4096);
			mailslotControl.EnableRead = false;
		}

		private void mailslotControl_ReadClicked(object sender, EventArgs e)
		{
			mailslotControl.ReadText = _mailslotServer.ReadMessage();
		}

		private void mailslotControl_WriteClicked(object sender, EventArgs e)
		{
			_mailslotClient.SendMessage(mailslotControl.WriteText);
		}

		private void memoryMappedFileControl_ReadClicked(object sender, EventArgs e)
		{
			int count = BitConverter.ToInt32(_memoryMappedFile.ReadBytes(0, 4), 0);
			memoryMappedFileControl.ReadText = Encoding.ASCII.GetString(_memoryMappedFile.ReadBytes(4, count));
		}

		private void memoryMappedFileControl_WriteClicked(object sender, EventArgs e)
		{
			string message = memoryMappedFileControl.WriteText;
			int count = message.Length;
			_memoryMappedFile.WriteBytes(BitConverter.GetBytes(count), 0, 4);
			_memoryMappedFile.WriteBytes(Encoding.ASCII.GetBytes(message), 4, count);
		}

		private void sharedMemoryControl_ReadClicked(object sender, EventArgs e)
		{
			int count = BitConverter.ToInt32(_sharedMemory.ReadBytes(0, 4), 0);
			sharedMemoryControl.ReadText = Encoding.ASCII.GetString(_sharedMemory.ReadBytes(4, count));
		}

		private void sharedMemoryControl_WriteClicked(object sender, EventArgs e)
		{
			string message = sharedMemoryControl.WriteText;
			int count = message.Length;
			_sharedMemory.WriteBytes(BitConverter.GetBytes(count), 0, 4);
			_sharedMemory.WriteBytes(Encoding.ASCII.GetBytes(message), 4, count);
		}

		private void Form1_FormClosed(object sender, FormClosedEventArgs e)
		{
			_mailslotServer.Dispose();
			_mailslotClient.Dispose();
			_memoryMappedFile.Dispose();
			_sharedMemory.Dispose();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			_mailslotServer.Create();
			(sender as Button).Enabled = false;
			mailslotControl.EnableRead = true;
		}
	}
}
